package com.smile.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.dtflys.forest.annotation.Get;
import com.smile.api.FlightTaskApi;
import com.smile.api.OperateLogApi;
import com.smile.api.UserApi;
import com.smile.commons.action.ActionUtils;
import com.smile.commons.file.FileUtils;
import com.smile.commons.gps.*;
import com.smile.commons.gps.domain.CoordinatePointReq;
import com.smile.commons.gps.domain.MappingTypeReq;
import com.smile.commons.gps.kml.CollectionMethodEnums;
import com.smile.commons.gps.kml.LensTypeEnums;
import com.smile.commons.gps.kml.ShootTypeEnums;
import com.smile.commons.page.MyBatisPlusPageConverter;
import com.smile.commons.page.R;
import com.smile.commons.random.SnowFlakeUtil;
import com.smile.commons.request.RequestIdUtils;
import com.smile.file.uitl.MinioUtil;
import com.smile.mapper.*;
import com.smile.mapper.AirLineMapper;
import com.smile.model.dao.AirlineDAO;
import com.smile.model.domain.*;
import com.smile.model.dto.request.*;
import com.smile.model.request.GenerateAirlineFileRequest;
import com.smile.model.request.GeneratePlanarAirlineRequest;
import com.smile.model.response.GenerateAirlineFileResponse;
import com.smile.model.response.GetUserByIdResponse;
import com.smile.model.response.PutFileResponse;
import com.smile.model.response.response.*;
import com.smile.request.AddOperateLogRequest;
import com.smile.service.AirlineService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.dynamictp.core.executor.DtpExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smile.commons.gps.domain.CoordinatePointReq;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Service
@Slf4j
public class AirlineServiceImpl implements AirlineService {

    @Autowired
    private AirLineMapper airlineMapper;

    @Autowired
    private UserApi userApi;

    @Autowired
    private OperateLogApi operateLogApi;

    @Autowired
    private WayPointMapper wayPointMapper;

    @Autowired
    private WayPointActionMapper wayPointActionMapper;

    @Autowired
    private MegaphoneOperateMapper megaphoneOperateMapper;

    @Autowired
    private AlgorithmMapper algorithmMapper;

    @Autowired
    private FlightTaskApi flightTaskApi;

    @Autowired
    private DeviceModelMapper deviceMapper;
    @Autowired
    private AlgorithmExtendsMapper algorithmExtendsMapper;


    @Autowired
    private DtpExecutor dtpExecutor0;

    @Autowired
    private PlanarAirlineMapper planarAirlineMapper;

    @Autowired
    private CoordinatePointMapper coordinatePointMapper;


    @Autowired
    private DeviceModelMapper deviceModelMapper;


//    public void convertPosition(AddWayPointRequestDTO wayPoint) {
//        if (wayPoint.getPositionType() == 1) {
//            //百度转大疆
//            //lng lat
//            BigDecimal[] bigDecimals = CoordinateTransformUtil.gcj02ToWgs84(wayPoint.getLongitude().doubleValue(), wayPoint.getLatitude());
//            wayPoint.setLongitude(bigDecimals[0]);
//            wayPoint.setLatitude(bigDecimals[1]);
//        }
//        if (wayPoint.getPositionType() == 2) {
//            //高德转大疆
//            BigDecimal[] bigDecimals = CoordinateTransformUtil.bd09ToWgs84(wayPoint.getLongitude(), wayPoint.getLatitude());
//            wayPoint.setLongitude(bigDecimals[0]);
//            wayPoint.setLatitude(bigDecimals[1]);
//        }
//    }

    public static void main(String[] args) {
        //30.249789,119.902068
        CoordinateTransformUtil.Coordinate coordinate1 = CoordinateTransformUtil.gcj02ToWgs84(new BigDecimal("30.249789"), new BigDecimal("119.902068"));
        System.out.println(coordinate1.getLatitude());
        System.out.println(coordinate1.getLongitude());


//        double[] doubles = GeoConvertUtils.gaodeToGps(Double.valueOf(new BigDecimal("39.59800491077882").setScale(6, RoundingMode.HALF_UP).doubleValue()),Double.valueOf(new BigDecimal("118.1804858669555").setScale(6, RoundingMode.HALF_UP).doubleValue()) );
//
//        System.out.println(doubles[0]);
//        System.out.println(doubles[1]);
//
//        double[] doubles1 = GeoConvertUtils.gpsToGaode(new BigDecimal(String.valueOf(Double.valueOf(doubles[0]))).setScale(6,RoundingMode.HALF_UP).doubleValue(),new BigDecimal(String.valueOf(Double.valueOf(doubles[1]))).setScale(6,RoundingMode.HALF_UP).doubleValue());
//        System.out.println(new BigDecimal(String.valueOf(doubles1[0])).setScale(6, RoundingMode.HALF_UP).doubleValue());
//        System.out.println(new BigDecimal(String.valueOf(doubles1[1])).setScale(6, RoundingMode.HALF_UP).doubleValue());

//        wayPoint.setLatitude(new BigDecimal(Double.toString(doubles[0])).setScale(6, BigDecimal.ROUND_HALF_UP));
//        wayPoint.setLongitude(new BigDecimal(Double.toString(doubles[1])).setScale(6, BigDecimal.ROUND_HALF_UP));

//        BigDecimal[] bigDecimals = CoordinateTransformUtil.gcj02ToWgs84(new BigDecimal("39.596704"), new BigDecimal("118.174213"));
//
//        System.out.println(bigDecimals[0]);
//        System.out.println(bigDecimals[1]);

//        BigDecimal[] bigDecimals1 = CoordinateTransformUtil.wgs84ToGcj02(bigDecimals[0], bigDecimals[1]);
//        System.out.println(bigDecimals1[0].setScale(6, RoundingMode.HALF_UP));
//        System.out.println(bigDecimals1[1].setScale(6, RoundingMode.HALF_UP));

        //                wayPoint.setLongitude(bigDecimals[0]);
//                wayPoint.setLatitude(bigDecimals[1]);

//        Gps gps = PositionUtil.gps84_To_Gcj02(38.99430398933626d, 196.74022082004626d);
//        System.out.println(gps.getWgLon());
//        System.out.println(gps.getWgLat());

        //高德坐标转大疆
//        BigDecimal[] bigDecimals = CoordinateTransformUtil.wgs84ToGcj02(new BigDecimal("118.15871885441824"), new BigDecimal("39.58719797629177"));
////        BigDecimal[] bigDecimals = CoordinateTransformUtil.stringGcj02ToWgs84(wayPoint.getLongitude(), wayPoint.getLatitude());
//        System.out.println(bigDecimals[0]);
//        System.out.println(bigDecimals[1]);
    }
    @Override
    @Transactional
    public Long addAirlineName(AddAirlineRequestDTO addAirlineRequestDTO) {
        Long startTime = System.currentTimeMillis();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        long loginIdAsLong = StpUtil.getLoginIdAsLong();
        FeisuanAirline feisuanAirline = BeanUtil.copyProperties(addAirlineRequestDTO, FeisuanAirline.class);
        QueryWrapper<FeisuanAirline> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("airline_name", addAirlineRequestDTO.getAirlineName());
        queryWrapper.eq("is_copy",0);
        queryWrapper.last("limit 1");
        FeisuanAirline feisuanAirline1 = airlineMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(feisuanAirline1)) {
            return null;
        }
        feisuanAirline.setCreateTime(LocalDateTime.now());
        feisuanAirline.setUserId(loginIdAsLong);
        feisuanAirline.setAirlineCode(UUID.randomUUID().toString());
        airlineMapper.insert(feisuanAirline);
        Long endTime = System.currentTimeMillis();
        saveLog("任务模块", "新增航线", 1, endTime - startTime);
        return feisuanAirline.getId();
    }
    @Override
    @Transactional
    public Boolean editAirlineName(EditAirlineRequestDTO editAirlineRequestDTO) {

        Long startTime = System.nanoTime();


        FeisuanAirline feisuanAirline = airlineMapper.selectById(editAirlineRequestDTO.getId());
        if (ObjectUtil.isNull(feisuanAirline)) {
            throw new RuntimeException("航线不存在");
        }
        QueryWrapper<FeisuanAirline> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("airline_name", editAirlineRequestDTO.getAirlineName());

        queryWrapper.ne("id", editAirlineRequestDTO.getId());
        queryWrapper.eq("is_copy",0);
        queryWrapper.last("limit 1");
        FeisuanAirline feisuanAirline1 = airlineMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(feisuanAirline1)) {
            return Boolean.FALSE;
        }
        UpdateWrapper<FeisuanAirline> updateWrapper = new UpdateWrapper<>();
        if (ObjectUtil.isNotNull(editAirlineRequestDTO)) {
            updateWrapper.eq(ObjectUtil.isNotNull(editAirlineRequestDTO.getId()), "id", editAirlineRequestDTO.getId()).
                    set(StrUtil.isNotBlank(editAirlineRequestDTO.getAirlineName()),
                            "airline_name", editAirlineRequestDTO.getAirlineName())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getAirlineType()), "airline_type", editAirlineRequestDTO.getAirlineType())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getBrandId()), "brand_id", editAirlineRequestDTO.getBrandId())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getSeriesId()), "series_id", editAirlineRequestDTO.getSeriesId())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getModelId()), "model_id", editAirlineRequestDTO.getModelId());

            airlineMapper.update(null, updateWrapper);



            Long endTime = System.nanoTime();

            AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
            addOperateLogRequest.setOperateModule("任务模块");
            addOperateLogRequest.setOperateName("编辑航线名称");
            addOperateLogRequest.setOperateResult(Boolean.TRUE);
            addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
            addOperateLogRequest.setOperateType(2);
            addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
            addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
            addOperateLogRequest.setTimes(endTime - startTime);
            operateLogApi.addOperateLogRequest(addOperateLogRequest);

            return Boolean.TRUE;
        } else {

            return Boolean.FALSE;
        }

    }

    @Override
    @Transactional
    public Boolean addAirline(AddAirlineRequestDTO addAirlineRequestDTO) {

        if (CollectionUtil.isEmpty(addAirlineRequestDTO.getWayPoints())) {
            throw new RuntimeException("航线至少有一个航点");
        }
        QueryWrapper<FeisuanAirline> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("airline_name", addAirlineRequestDTO.getAirlineName());
        queryWrapper.last("limit 1");
        FeisuanAirline feisuanAirline1 = airlineMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(feisuanAirline1)) {
            throw new RuntimeException("名称已存在");
        }
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        long loginIdAsLong = StpUtil.getLoginIdAsLong();
        dtpExecutor0.execute(() -> {

            try {
                Long startTime = System.nanoTime();

                //存储基础航线信息到数据库


                FeisuanAirline feisuanAirline = BeanUtil.copyProperties(addAirlineRequestDTO, FeisuanAirline.class);
                feisuanAirline.setCreateTime(LocalDateTime.now());
                feisuanAirline.setUserId(loginIdAsLong);
                feisuanAirline.setAirlineCode(UUID.randomUUID().toString());
                airlineMapper.insert(feisuanAirline);

                String[] split = addAirlineRequestDTO.getTakeOffRefPoint().split(",");


                CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.gcj02ToWgs84(new BigDecimal(split[0]), new BigDecimal(split[1]));
                feisuanAirline.setTakeOffRefPoint(coordinate.getLatitude().setScale(6, RoundingMode.HALF_UP) + "," + coordinate.getLongitude().setScale(6, RoundingMode.HALF_UP) + "," + addAirlineRequestDTO.getTakeOffSecurityHeight().setScale(6, RoundingMode.HALF_UP));
                addAirlineRequestDTO.setTakeOffRefPoint(coordinate.getLatitude().setScale(6, RoundingMode.HALF_UP) + "," + coordinate.getLongitude().setScale(6, RoundingMode.HALF_UP) + "," + addAirlineRequestDTO.getTakeOffSecurityHeight().setScale(6, RoundingMode.HALF_UP));
                AtomicInteger waypointIdTemp = new AtomicInteger(0);
                AtomicInteger waypointActionIdTemp = new AtomicInteger(0);

                //坐标转换
                addAirlineRequestDTO.getWayPoints().forEach(wayPoint -> {

//            log.info("执行坐标转换操作,操作用户id为{},requestId={},转换前的坐标为:{}", StpUtil.getLoginId(), RequestIdUtils.get(), wayPoint.getLongitude() + "," + wayPoint.getLatitude());

                    //坐标转换
//                convertPosition(wayPoint);


//                double[] doubles = GeoConvertUtils.gaodeToGps(wayPoint.getLatitude().doubleValue(), wayPoint.getLongitude().doubleValue());
//                wayPoint.setLatitude(new BigDecimal(Double.toString(doubles[0])));
//                wayPoint.setLongitude(new BigDecimal(Double.toString(doubles[1])));

//            log.info("执行坐标转换操作,操作用户id为{},requestId={},转换后的坐标为:{}", StpUtil.getLoginId(), RequestIdUtils.get(), wayPoint.getLongitude() + "," + wayPoint.getLatitude());


                    FeisuanWayPoint feisuanWayPoint = BeanUtil.copyProperties(wayPoint, FeisuanWayPoint.class);
                    feisuanWayPoint.setAirlineId(feisuanAirline.getId());
                    int index = waypointIdTemp.getAndIncrement();
                    feisuanWayPoint.setIndex(index);
                    wayPoint.setIndex(index);

                    wayPointMapper.insert(feisuanWayPoint);

                    CoordinateTransformUtil.Coordinate coordinate1 = CoordinateTransformUtil.gcj02ToWgs84(wayPoint.getLongitude().setScale(6, RoundingMode.HALF_UP), wayPoint.getLatitude().setScale(6, RoundingMode.HALF_UP));
                    wayPoint.setLatitude(coordinate1.getLatitude().setScale(6, RoundingMode.HALF_UP));
                    wayPoint.setLongitude(coordinate1.getLongitude().setScale(6, RoundingMode.HALF_UP));

                    wayPoint.getAlgorithmIds().forEach(algorithmId -> {
                        FeisuanAlgorithm feisuanAlgorithm = new FeisuanAlgorithm();
                        feisuanAlgorithm.setAlgorithmId(algorithmId);
                        feisuanAlgorithm.setWayPointId(feisuanWayPoint.getId());
                        algorithmMapper.insert(feisuanAlgorithm);
                    });

                    if (CollectionUtil.isNotEmpty(wayPoint.getAlgorithmExtends())) {
                        //存储算法的扩展信息
                        List<FeisuanAlgorithmExtends> collect = wayPoint.getAlgorithmExtends().stream()
                                .map(addAlgorithmExtendsRequestDTO -> {
                                    FeisuanAlgorithmExtends feisuanAlgorithmExtends = BeanUtil.copyProperties(addAlgorithmExtendsRequestDTO, FeisuanAlgorithmExtends.class);
                                    feisuanAlgorithmExtends.setWayPointId(feisuanWayPoint.getId());
                                    return feisuanAlgorithmExtends;
                                }).collect(Collectors.toList());
                        collect.forEach(feisuanAlgorithmExtends -> {
                            algorithmExtendsMapper.insert(feisuanAlgorithmExtends);
                        });
                    }


                    //存储航点动作
                    wayPoint.getActions().forEach(action -> {
                        int waypointActionId = waypointActionIdTemp.getAndIncrement();

                        FeisuanWayPointAction feisuanWayPointAction = BeanUtil.copyProperties(action, FeisuanWayPointAction.class);
                        feisuanWayPointAction.setWayPointId(feisuanWayPoint.getId());
                        feisuanWayPointAction.setIndex(waypointActionId);
                        action.setIndex(waypointActionId);
                        wayPointActionMapper.insert(feisuanWayPointAction);
                    });


                    //存储喊话配置
                    AddMegaphoneOperateRequestDTO megaphoneOperate = wayPoint.getMegaphoneOperate();
                    FeisuanMegaphoneOperate feisuanMegaphoneOperate = BeanUtil.copyProperties(megaphoneOperate, FeisuanMegaphoneOperate.class);

                    feisuanMegaphoneOperate.setWayPointId(feisuanWayPoint.getId());
                    megaphoneOperateMapper.insert(feisuanMegaphoneOperate);

                });


                GenerateAirlineFileRequest generateAirlineFileRequest = BeanUtil.copyProperties(addAirlineRequestDTO, GenerateAirlineFileRequest.class);
                Long l = SnowFlakeUtil.generateId();

                generateAirlineFileRequest.getWayPoints().forEach(wayPoint -> {
                    wayPoint.setIndex(l.intValue());
                });

//        log.info("执行生成航线文件操作,操作用户id为{},requestId={}", StpUtil.getLoginId(), RequestIdUtils.get());

                RequestContextHolder.setRequestAttributes(requestAttributes);
                R<GenerateAirlineFileResponse> generateAirlineFileResponseR = flightTaskApi.generateAirlineFile(generateAirlineFileRequest);

                //更新航线文件信息功能
                if (ObjectUtil.isNotNull(generateAirlineFileResponseR) && ObjectUtil.isNotNull(generateAirlineFileResponseR.getData())) {

//            log.info("开始执行生成航线文件操作,操作用户id为{},requestId={}", StpUtil.getLoginId(), RequestIdUtils.get());

                    feisuanAirline.setAirlineUrl(generateAirlineFileResponseR.getData().getUrl());
                    feisuanAirline.setETag(generateAirlineFileResponseR.getData().getETag());
                    UpdateWrapper<FeisuanAirline> feisuanAirlineUpdateWrapper = new UpdateWrapper<>();
                    feisuanAirlineUpdateWrapper.eq("id", feisuanAirline.getId())
                            .set("airline_url", generateAirlineFileResponseR.getData().getUrl())
                            .set("e_tag", generateAirlineFileResponseR.getData().getETag());


                    airlineMapper.update(null, feisuanAirlineUpdateWrapper);
                }


                Long endTime = System.nanoTime();

                //存储日志
                saveLog("任务模块", "新增航线", 1, endTime - startTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });


        return Boolean.TRUE;
    }

    private void saveLog(String operateModule, String operateName, Integer operateType, Long time) {
        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
        addOperateLogRequest.setOperateModule(operateModule);
        addOperateLogRequest.setOperateName(operateName);
        addOperateLogRequest.setOperateResult(Boolean.TRUE);
        if (StpUtil.isLogin()) {
            addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        } else {
//        addOperateLogRequest.setUserId(111L);
        }
        addOperateLogRequest.setOperateType(operateType);
        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
        addOperateLogRequest.setTimes(time);
        operateLogApi.addOperateLogRequest(addOperateLogRequest);
    }


    @Override
    public Page<GetAirLineListResponseDTO> getAirlineList(GetAirlineListRequestDTO getAirlineListRequestDTO) {
        if (StpUtil.isLogin()) {
            log.info("开始执行查询航线列表操作,操作用户id为{},requestId={}", StpUtil.getLoginId(), RequestIdUtils.get());
        }
        Page<AirlineDAO> airlineDAOIPage = new Page<>(getAirlineListRequestDTO.getCurrentPage(), getAirlineListRequestDTO.getPageSize());
        airlineDAOIPage.addOrder(OrderItem.desc("createTime"), OrderItem.desc("id"));

        Page<AirlineDAO> airlineList = airlineMapper.getAirlineList(airlineDAOIPage, getAirlineListRequestDTO.getAirlineName(),getAirlineListRequestDTO.getModelId());


//        Page<GetAirLineListResponseDTO> getAirLineListResponseDTOPage = MyBatisPlusPageConverter.convertPage(feisuanAirlinePage, GetAirLineListResponseDTO.class);

        Page<GetAirLineListResponseDTO> getAirLineListResponseDTOPage = MyBatisPlusPageConverter.convertPage(airlineList, GetAirLineListResponseDTO.class);

        List<Long> collect = airlineList.getRecords().stream().map(i -> i.getUserId()).collect(Collectors.toList());

        if (ObjectUtil.isNotNull(collect)) {

            R<Map<Long, GetUserByIdResponse>> userByIds = userApi.getUserByIds(collect);
            getAirLineListResponseDTOPage.setRecords(airlineList.getRecords().stream()
                    .sorted((airline1, airline2) -> {
                        return airline2.getCreateTime().compareTo(airline1.getCreateTime());
                    })
                    .map(i -> {
                        GetAirLineListResponseDTO getAirLineListResponseDTO = BeanUtil.copyProperties(i, GetAirLineListResponseDTO.class);
                        if (i.getAirlineType() != null) {

                            switch (i.getAirlineType()) {
                                case 0:
                                    getAirLineListResponseDTO.setAirlineType("点状航线");
                                    break;
                                case 1:
                                    getAirLineListResponseDTO.setAirlineType("面状航线");
                                    break;
                            }
                        }
                        if (ObjectUtil.isNotNull(i.getTotalDistance()) && i.getTotalDistance() ==0) {
                            getAirLineListResponseDTO.setTotalDistance(null);
                        }

                        if ( ObjectUtil.isNotNull(i.getExecuteTime()) && i.getExecuteTime().equals("0")) {
                            getAirLineListResponseDTO.setExecuteTime(null);
                        }

                        if (ObjectUtil.isNotNull(userByIds) && ObjectUtil.isNotNull(userByIds.getData())
                                && ObjectUtil.isNotNull(userByIds.getData().get(i.getUserId()))) {
                            getAirLineListResponseDTO.setUserName(userByIds.getData().get(i.getUserId()).getUserName());
                        }

                        FeisuanDeviceModel feisuanDeviceModel =  deviceModelMapper.selectById(i.getModelId());
                        if (ObjectUtil.isNotNull(feisuanDeviceModel)) {
                            getAirLineListResponseDTO.setModelName(feisuanDeviceModel.getModelName());
                            getAirLineListResponseDTO.setDeviceModelKey(feisuanDeviceModel.getDeviceModelKey());
                        }
                        return getAirLineListResponseDTO;
                    }).collect(Collectors.toList()));
        }

//        List<GetAirLineListResponseDTO> records = getAirLineListResponseDTOPage.getRecords();
//        GetAirLineListResponseDTO getAirLineListResponseDTO = new GetAirLineListResponseDTO();
//        getAirLineListResponseDTO.setAirlineType("面状啊韩国女星");
//        getAirLineListResponseDTO.setId(8L);
//        getAirLineListResponseDTO.setAirlineUrl("http://www.smile-emo.com/kml/file/kmz/684dcb7548e8401cbca11a8c514842f3.kmz");
//        getAirLineListResponseDTO.setAirlineName("面状航线");
//        getAirLineListResponseDTO.setCreateTime(LocalDateTime.now());
//        getAirLineListResponseDTO.setExecuteTime("8s");
//        records.add(getAirLineListResponseDTO);
//        getAirLineListResponseDTOPage.setRecords(records);

        if (StpUtil.isLogin()) {
            log.info("执行查询航线列表操作完成,操作用户id为{},requestId={},查询出来的数据为=:{}", StpUtil.getLoginId(), RequestIdUtils.get(), getAirLineListResponseDTOPage);
        }

        return getAirLineListResponseDTOPage;
    }

    @Override
    @Transactional
    public Boolean editAirline(EditAirlineRequestDTO editAirlineRequestDTO) {

        Long startTime = System.nanoTime();

        if (CollectionUtil.isEmpty(editAirlineRequestDTO.getWayPoints())) {
            throw new RuntimeException("航线至少有一个航点");
        }

        FeisuanAirline feisuanAirline = airlineMapper.selectById(editAirlineRequestDTO.getId());
        if (ObjectUtil.isNull(feisuanAirline)) {
            throw new RuntimeException("航线不存在");
        }
        if (ObjectUtil.isNull(editAirlineRequestDTO.getIrType()) && ObjectUtil.isNotNull(editAirlineRequestDTO.getVisableType()) && ObjectUtil.isNotNull(editAirlineRequestDTO.getWideType())) {
            throw new RuntimeException("至少选择一种照片存储类型");
        }

        QueryWrapper<FeisuanAirline> queryWrapperOld = new QueryWrapper<>();
        queryWrapperOld.eq("airline_name", editAirlineRequestDTO.getAirlineName());

        queryWrapperOld.ne("id", editAirlineRequestDTO.getId());
        queryWrapperOld.last("limit 1");
        queryWrapperOld.eq("is_copy",0);
        FeisuanAirline feisuanAirline1 = airlineMapper.selectOne(queryWrapperOld);
        if (ObjectUtil.isNotNull(feisuanAirline1)) {
            throw new RuntimeException("航线名称已存在");
        }

        UpdateWrapper<FeisuanAirline> updateWrapper = new UpdateWrapper<>();
        if (ObjectUtil.isNotNull(editAirlineRequestDTO)) {

            updateWrapper.eq(ObjectUtil.isNotNull(editAirlineRequestDTO.getId()), "id", editAirlineRequestDTO.getId()).
                    set(StrUtil.isNotBlank(editAirlineRequestDTO.getAirlineName()),
                            "airline_name", editAirlineRequestDTO.getAirlineName())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getAirlineType()), "airline_type", editAirlineRequestDTO.getAirlineType())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getWideType()), "wide_type", editAirlineRequestDTO.getWideType())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getZoomType()), "zoom_type", editAirlineRequestDTO.getZoomType())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getIrType()), "ir_type", editAirlineRequestDTO.getIrType())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getAirlineHeightType()), "airline_height_type", editAirlineRequestDTO.getAirlineHeightType())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getGlobalHeight()), "global_height", editAirlineRequestDTO.getGlobalHeight())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getAutoFlightSpeed()), "auto_flight_speed", editAirlineRequestDTO.getAutoFlightSpeed())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getGlobalTransitionalSpeed()), "global_transitional_speed", editAirlineRequestDTO.getGlobalTransitionalSpeed())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getAttitudeHead()), "attitude_head", editAirlineRequestDTO.getAttitudeHead())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getWayPointType()), "way_point_type", editAirlineRequestDTO.getWayPointType())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getOutOfControlAction()), "out_of_control_action", editAirlineRequestDTO.getOutOfControlAction())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getFinishAction()), "finish_action", editAirlineRequestDTO.getFinishAction())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getTakeOffSecurityHeight()), "take_off_security_height", editAirlineRequestDTO.getTakeOffSecurityHeight())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getGlobalRTHHeight()), "global_RTH_height", editAirlineRequestDTO.getGlobalRTHHeight())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getPointNum()), "point_num", editAirlineRequestDTO.getPointNum())
                    .set(StrUtil.isNotBlank(editAirlineRequestDTO.getExecuteTime()), "execute_time", editAirlineRequestDTO.getExecuteTime())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getTotalDistance()), "total_distance", editAirlineRequestDTO.getTotalDistance())
                    .set(StrUtil.isNotBlank(editAirlineRequestDTO.getAirportName()), "airport_name", editAirlineRequestDTO.getAirportName())
                    .set(StrUtil.isNotBlank(editAirlineRequestDTO.getAirportPosition()), "airport_position", editAirlineRequestDTO.getAirportPosition())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getAirportId()), "airport_id", editAirlineRequestDTO.getAirportId())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getBrandId()), "brand_id", editAirlineRequestDTO.getBrandId())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getSeriesId()), "series_id", editAirlineRequestDTO.getSeriesId())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getModelId()), "model_id", editAirlineRequestDTO.getModelId())
                    .set(ObjectUtil.isNotNull(editAirlineRequestDTO.getVisableType()), "visable_type", editAirlineRequestDTO.getVisableType())
                    .set(StrUtil.isNotBlank(editAirlineRequestDTO.getTakeOffRefPoint()), "take_off_ref_point", editAirlineRequestDTO.getTakeOffRefPoint());


            airlineMapper.update(null, updateWrapper);
            System.out.println("visable"+editAirlineRequestDTO.getVisableType());
            if (StrUtil.isNotBlank(editAirlineRequestDTO.getTakeOffRefPoint())) {
//                updateWrapper.set("take_off_ref_point", s1);
                String[] split = editAirlineRequestDTO.getTakeOffRefPoint().split(",");


                CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.gcj02ToWgs84(new BigDecimal(split[0]), new BigDecimal(split[1]));
                feisuanAirline.setTakeOffRefPoint(coordinate.getLatitude().setScale(6, RoundingMode.HALF_UP) + "," + coordinate.getLongitude().setScale(6, RoundingMode.HALF_UP) + "," + editAirlineRequestDTO.getTakeOffSecurityHeight().setScale(6, RoundingMode.HALF_UP));
                editAirlineRequestDTO.setTakeOffRefPoint(coordinate.getLatitude().setScale(6, RoundingMode.HALF_UP) + "," + coordinate.getLongitude().setScale(6, RoundingMode.HALF_UP) + "," + editAirlineRequestDTO.getGlobalRTHHeight().setScale(6, RoundingMode.HALF_UP));
            }

            QueryWrapper<FeisuanWayPoint> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("airline_id", editAirlineRequestDTO.getId());
            List<FeisuanWayPoint> feisuanWayPoints = wayPointMapper.selectList(queryWrapper);
            feisuanWayPoints.forEach(wayPoint -> {
                QueryWrapper<FeisuanWayPointAction> feisuanWayPointActionQueryWrapper = new QueryWrapper<>();
                feisuanWayPointActionQueryWrapper.eq("way_point_id", wayPoint.getId());
                wayPointActionMapper.delete(feisuanWayPointActionQueryWrapper);

                QueryWrapper<FeisuanAlgorithm> feisuanAlgorithmQueryWrapper = new QueryWrapper<>();
                feisuanAlgorithmQueryWrapper.eq("way_point_id", wayPoint.getId());
                algorithmMapper.delete(feisuanAlgorithmQueryWrapper);

                QueryWrapper<FeisuanMegaphoneOperate> megaphoneOperateQueryWrapper = new QueryWrapper<>();
                megaphoneOperateQueryWrapper.eq("way_point_id", wayPoint.getId());
                megaphoneOperateMapper.delete(megaphoneOperateQueryWrapper);

                QueryWrapper<FeisuanAlgorithmExtends> feisuanAlgorithmExtendsQueryWrapper = new QueryWrapper<>();
                feisuanAlgorithmExtendsQueryWrapper.eq("way_point_id", wayPoint.getId());
                algorithmExtendsMapper.delete(feisuanAlgorithmExtendsQueryWrapper);
            });
            wayPointMapper.delete(queryWrapper);
            editAirlineRequestDTO.getWayPoints().forEach(wayPoint -> {
                int i = SnowFlakeUtil.generateId().intValue();
                wayPoint.setIndex(i);

                FeisuanWayPoint feisuanWayPoint = BeanUtil.copyProperties(wayPoint, FeisuanWayPoint.class);
                feisuanWayPoint.setAirlineId(editAirlineRequestDTO.getId());
                feisuanWayPoint.setIndex(i);
                wayPointMapper.insert(feisuanWayPoint);

                CoordinateTransformUtil.Coordinate coordinate1 = CoordinateTransformUtil.gcj02ToWgs84(wayPoint.getLongitude().setScale(6, RoundingMode.HALF_UP), wayPoint.getLatitude().setScale(6, RoundingMode.HALF_UP));
                wayPoint.setLatitude(coordinate1.getLatitude().setScale(6, RoundingMode.HALF_UP));
                wayPoint.setLongitude(coordinate1.getLongitude().setScale(6, RoundingMode.HALF_UP));

                if (CollectionUtil.isNotEmpty(wayPoint.getAlgorithmIds())) {
                    wayPoint.getAlgorithmIds().forEach(algorithmId -> {
                        FeisuanAlgorithm feisuanAlgorithm = new FeisuanAlgorithm();
                        feisuanAlgorithm.setAlgorithmId(algorithmId);
                        feisuanAlgorithm.setWayPointId(feisuanWayPoint.getId());
                        algorithmMapper.insert(feisuanAlgorithm);
                    });
                }
                if (CollectionUtil.isNotEmpty(wayPoint.getAlgorithmExtends())) {

                    List<FeisuanAlgorithmExtends> collect = wayPoint.getAlgorithmExtends().stream()
                            .map(addAlgorithmExtendsRequestDTO -> {
                                FeisuanAlgorithmExtends feisuanAlgorithmExtends = BeanUtil.copyProperties(addAlgorithmExtendsRequestDTO, FeisuanAlgorithmExtends.class);
                                feisuanAlgorithmExtends.setWayPointId(feisuanWayPoint.getId());
                                return feisuanAlgorithmExtends;
                            }).collect(Collectors.toList());
                    collect.forEach(feisuanAlgorithmExtends -> {
                        algorithmExtendsMapper.insert(feisuanAlgorithmExtends);
                    });
                }

//                Db.saveBatch(dataToSaveBatch);


                wayPoint.getActions().forEach(action -> {
                    int i1 = SnowFlakeUtil.generateId().intValue();
                    action.setIndex(i1);
                    action.setIndex(i1);
                    FeisuanWayPointAction feisuanWayPointAction = BeanUtil.copyProperties(action, FeisuanWayPointAction.class);
                    System.out.println("航点动作:"+feisuanWayPointAction);
                    feisuanWayPointAction.setWayPointId(feisuanWayPoint.getId());
                    wayPointActionMapper.insert(feisuanWayPointAction);
                });

                GenerateAirlineFileRequest generateAirlineFileRequest = BeanUtil.copyProperties(editAirlineRequestDTO, GenerateAirlineFileRequest.class);

                AtomicInteger indexNum = new AtomicInteger(0);

                generateAirlineFileRequest.getWayPoints().forEach(wayPoint1 -> {
                    wayPoint1.setIndex(indexNum.getAndIncrement());
                });

                System.out.println("航线类别:"+generateAirlineFileRequest.getAirlineType());
                generateAirlineFileRequest.setAirlineType(0);
//                FeisuanDeviceModel feisuanDeviceModel = deviceMapper.selectById(editAirlineRequestDTO.getModelId());
//                System.out.println("无人机型号:"+JSON.toJSONString(feisuanDeviceModel));
//                if (ObjectUtil.isNotNull(feisuanDeviceModel)) {
//                    wpmzConfig.setDroneEnumValue(Integer.valueOf( feisuanDeviceModel.getType()));
//                    wpmzConfig.setDroneSubEnumValue(Integer.valueOf(feisuanDeviceModel.getSubType()));
//                }
                R<GenerateAirlineFileResponse> generateAirlineFileResponseR = flightTaskApi.generateAirlineFile(generateAirlineFileRequest);

                if (ObjectUtil.isNotNull(generateAirlineFileResponseR) && ObjectUtil.isNotNull(generateAirlineFileResponseR.getData())) {
                    UpdateWrapper<FeisuanAirline> feisuanAirlineUpdateWrapper = new UpdateWrapper<>();
                    feisuanAirlineUpdateWrapper.eq("id", feisuanAirline.getId())
                            .set("airline_url", generateAirlineFileResponseR.getData().getUrl())
                            .set("e_tag", generateAirlineFileResponseR.getData().getETag());
                    airlineMapper.update(null, feisuanAirlineUpdateWrapper);
                }


                EditMegaphoneOperateRequestDTO megaphoneOperate = wayPoint.getMegaphoneOperate();
                FeisuanMegaphoneOperate feisuanMegaphoneOperate = BeanUtil.copyProperties(megaphoneOperate, FeisuanMegaphoneOperate.class);


//                if (megaphoneOperate.getMegaphoneType() == 0) {
//                    try {
//                        String s = WebTtsWs.generateFile(megaphoneOperate.getText());
//                        File file = new File(s);
//                        String s1 = UUID.randomUUID().toString().replaceAll("-", "") + ".pcm";
//                        MultipartFile multipartFile = FileUtils.fileToMultipartFile(file, s1);
//                        PutFileRequest putFileRequest = new PutFileRequest();
//                        putFileRequest.setPath(file.getAbsolutePath());
//                        putFileRequest.setFileName(s1);
//                        putFileRequest.setPutFileRequest(multipartFile);
//                        R<PutFileResponse> putFileResponseR = ossApi.putFile(FileUtils.SHOUT_FILE_PATH, s1, multipartFile);
//                        if (ObjectUtil.isNotNull(putFileResponseR) && ObjectUtil.isNotNull(putFileResponseR.getData())) {
//                            String url = putFileResponseR.getData().getUrl();
//                            feisuanMegaphoneOperate.setMegaphoneOperateFile(url);
//
//                        }
//                    } catch (Exception e) {
//                        throw new RuntimeException(e);
//                    }
//                }


                feisuanMegaphoneOperate.setWayPointId(feisuanWayPoint.getId());
                feisuanMegaphoneOperate.setId(null);
                megaphoneOperateMapper.insert(feisuanMegaphoneOperate);

            });


            Long endTime = System.nanoTime();


            AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
            addOperateLogRequest.setOperateModule("任务模块");
            addOperateLogRequest.setOperateName("编辑航线");
            addOperateLogRequest.setOperateResult(Boolean.TRUE);
            addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
            addOperateLogRequest.setOperateType(2);
            addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
            addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
            addOperateLogRequest.setTimes(endTime - startTime);
            operateLogApi.addOperateLogRequest(addOperateLogRequest);

            return Boolean.TRUE;
        } else {

            return Boolean.FALSE;
        }

    }

    @Override
    public GetAirlineByIdResponseDTO getAirlineById(GetAirlineByIdRequestDTO getAirlineByIdRequestDTO) {
        FeisuanAirline feisuanAirline = airlineMapper.selectById(getAirlineByIdRequestDTO.getId());
        System.out.println("航线查询");
        System.out.println(feisuanAirline);
        GetAirlineByIdResponseDTO getAirlineByIdResponseDTO = BeanUtil.copyProperties(feisuanAirline, GetAirlineByIdResponseDTO.class);
        QueryWrapper<FeisuanWayPoint> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("airline_id", feisuanAirline.getId());
        List<FeisuanWayPoint> feisuanWayPoints = wayPointMapper.selectList(queryWrapper);
        getAirlineByIdResponseDTO.setWayPoints(BeanUtil.copyToList(feisuanWayPoints, GetWayPointByIdResponseDTO.class));

        List<GetWayPointActionByIdResponseDTO> allActions = new ArrayList<>();
        List<GetWayPointByIdResponseDTO> wayPoints = new ArrayList<>();
//        getAirlineByIdResponseDTO.getWayPoints().forEach(wayPoint -> {
        for(GetWayPointByIdResponseDTO wayPoint:getAirlineByIdResponseDTO.getWayPoints()){
            QueryWrapper<FeisuanWayPointAction> feisuanWayPointActionQueryWrapper = new QueryWrapper<>();
            feisuanWayPointActionQueryWrapper.eq("way_point_id", wayPoint.getId());
            List<FeisuanWayPointAction> feisuanWayPointActions = wayPointActionMapper.selectList(feisuanWayPointActionQueryWrapper);
            List<GetWayPointActionByIdResponseDTO> actions = BeanUtil.copyToList(feisuanWayPointActions, GetWayPointActionByIdResponseDTO.class);

            wayPoint.setActions(actions);
            List<GetWayPointActionByIdResponseDTO> currentActions = new ArrayList<>();

            //检测是否有结束拍照
            boolean contains = actions.stream()
                    .anyMatch(obj -> obj.getActionType() == 11);
            for(GetWayPointActionByIdResponseDTO action : actions) {
                if(action.getActionType() == 9 || action.getActionType() == 10) {
                    System.out.println(action.getActionType());
                    allActions.add(action);
                }
            }

            currentActions = BeanUtil.copyToList(allActions, GetWayPointActionByIdResponseDTO.class);
            currentActions.addAll(actions);
            System.out.println(contains);
            if(contains) {
                if (!CollectionUtils.isEmpty(allActions)) {
                    allActions.removeIf(action->action.getActionType() == 9||action.getActionType() == 10);
                }
            }

            System.out.println(allActions);
            List<GetWayPointActionByIdResponseDTO> actions2 = BeanUtil.copyToList(currentActions, GetWayPointActionByIdResponseDTO.class);
            wayPoint.setSegmentActions(actions2);
            QueryWrapper<FeisuanAlgorithm> feisuanAlgorithmQueryWrapper = new QueryWrapper<>();
            feisuanAlgorithmQueryWrapper.eq("way_point_id", wayPoint.getId());
            List<FeisuanAlgorithm> feisuanAlgorithms = algorithmMapper.selectList(feisuanAlgorithmQueryWrapper);
            if (CollectionUtil.isNotEmpty(feisuanAlgorithms)) {
                List<Integer> collect = feisuanAlgorithms.stream().map(algorithm -> algorithm.getAlgorithmId()).collect(Collectors.toList());
                wayPoint.setAlgorithmIds(collect);
            } else {
                wayPoint.setAlgorithmIds(new ArrayList<>());
            }
            QueryWrapper<FeisuanAlgorithmExtends> feisuanAlgorithmExtendsQueryWrapper = new QueryWrapper<>();
            feisuanAlgorithmExtendsQueryWrapper.eq("way_point_id", wayPoint.getId());
            List<FeisuanAlgorithmExtends> feisuanAlgorithmExtends = algorithmExtendsMapper.selectList(feisuanAlgorithmExtendsQueryWrapper);
            if (CollectionUtil.isNotEmpty(feisuanAlgorithmExtends)) {

                wayPoint.setAlgorithmExtendsByIds(BeanUtil.copyToList(feisuanAlgorithmExtends, GetAlgorithmExtendsByIdResponseDTO.class));
            } else {
                wayPoint.setAlgorithmExtendsByIds(new ArrayList<>());
            }

            QueryWrapper<FeisuanMegaphoneOperate> feisuanMegaphoneOperateQueryWrapper = new QueryWrapper<>();
            feisuanMegaphoneOperateQueryWrapper.eq("way_point_id", wayPoint.getId());
            List<FeisuanMegaphoneOperate> feisuanMegaphoneOperates = megaphoneOperateMapper.selectList(feisuanMegaphoneOperateQueryWrapper);
            if (CollectionUtil.isNotEmpty(feisuanMegaphoneOperates)) {
                wayPoint.setMegaphoneOperate(BeanUtil.copyProperties(feisuanMegaphoneOperates.get(0), GetMegaphoneOperateByIdResponseDTO.class));
            }
            wayPoints.add(wayPoint);
        };
        getAirlineByIdResponseDTO.setWayPoints(wayPoints);
        return getAirlineByIdResponseDTO;
    }

    /**
     * 面状航线查询
     * @param getAirlineByIdRequestDTO
     * @return
     */
    @Override
    public UpdatePlanarAirlineResponseDTO getPlanarAirlineById(GetAirlineByIdRequestDTO getAirlineByIdRequestDTO) {
        FeisuanAirline feisuanAirline = airlineMapper.selectById(getAirlineByIdRequestDTO.getId());
        UpdatePlanarAirlineResponseDTO updatePlanarAirlineResponseDTO = BeanUtil.copyProperties(feisuanAirline, UpdatePlanarAirlineResponseDTO.class);

        //航点设置
        QueryWrapper<FeisuanWayPoint> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("airline_id", feisuanAirline.getId());
        List<FeisuanWayPoint> wayPoints = wayPointMapper.selectList(queryWrapper);

        if (CollectionUtil.isNotEmpty(wayPoints)) {
            List<CoordinatePointReq>coordinatePointReqList =  BeanUtil.copyToList(wayPoints, CoordinatePointReq.class);
            updatePlanarAirlineResponseDTO.setWayPoints(coordinatePointReqList);
        }

        QueryWrapper<FeisuanCoordinatePoint> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("airline_id", feisuanAirline.getId());
        List<FeisuanCoordinatePoint>  coordinatePointList = coordinatePointMapper.selectList(queryWrapper1);

        if (CollectionUtil.isNotEmpty(coordinatePointList)) {
            List<CoordinatePointReq>coordinatePointReqList1 =  BeanUtil.copyToList(coordinatePointList, CoordinatePointReq.class);
            updatePlanarAirlineResponseDTO.setCoordinatePointReqList(coordinatePointReqList1);
        }

        return updatePlanarAirlineResponseDTO;
    }


    @Override
    public Boolean deleteAirline(Long id) {
        QueryWrapper<FeisuanWayPoint> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("airline_id", id);
        List<FeisuanWayPoint> feisuanWayPoints = wayPointMapper.selectList(queryWrapper);
        feisuanWayPoints.forEach(wayPoint -> {
            QueryWrapper<FeisuanWayPointAction> feisuanWayPointActionQueryWrapper = new QueryWrapper<>();
            feisuanWayPointActionQueryWrapper.eq("way_point_id", wayPoint.getId());
            wayPointActionMapper.delete(feisuanWayPointActionQueryWrapper);

            QueryWrapper<FeisuanAlgorithm> feisuanAlgorithmQueryWrapper = new QueryWrapper<>();
            feisuanAlgorithmQueryWrapper.eq("way_point_id", wayPoint.getId());
            algorithmMapper.delete(feisuanAlgorithmQueryWrapper);

            QueryWrapper<FeisuanMegaphoneOperate> megaphoneOperateQueryWrapper = new QueryWrapper<>();
            megaphoneOperateQueryWrapper.eq("way_point_id", wayPoint.getId());
            megaphoneOperateMapper.delete(megaphoneOperateQueryWrapper);
        });
        wayPointMapper.delete(queryWrapper);
        airlineMapper.deleteById(id);
        return Boolean.TRUE;
    }

    @Override
    public Boolean deleteAirlineByOrganizationId(Long id) {
        QueryWrapper<FeisuanAirline> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organization_id", id);

        return Boolean.TRUE;
    }

    /**
     * 创建航线
     * @param
     * @throws IOException
     */
    @Override
    public GetPlanarAirlineResultResponseDTO generatorPlanarAirline(GeneratorPlanarAirlineRequestDTO generatorPlanarAirlineRequestDTO ) throws IOException {

        List<CoordinatePointReq> boundaryPoints = generatorPlanarAirlineRequestDTO.getCoordinatePointReqList();

        // 创建五角星形状
//        List<CoordinatePointReq> star = createStarShape();

        // 计算面积
        AreaCalculationUtil.AreaResult result2 = AreaCalculationUtil.calculatePolygonAreaWithFormat(boundaryPoints);
        double perimeter = AreaCalculationUtil.calculatePolygonPerimeter(boundaryPoints);

        System.out.println("五角星顶点数: " + boundaryPoints.size());
        System.out.println("格式化结果: " + result2);
        System.out.println("周长: " + String.format("%.2f", perimeter) + " 米");
        System.out.println();
        System.out.println("\n详细面积信息:");
        System.out.println("  - 平方米: " + result2.getSquareMetersFormatted() + " m²");
        System.out.println("  - 亩: " + result2.getMuFormatted() + " 亩");
        System.out.println("  - 公顷: " + result2.getHectaresFormatted() + " 公顷");
        System.out.println("  - 平方千米: " + result2.getSquareKilometersFormatted() + " km²");
        if (Float.valueOf(result2.getSquareMetersFormatted().toString()) > 7496502L){
            throw new RuntimeException("绘制面积过大，无法生成航线");
        }
        PlanarAirlineGenerator.AirlineConfig config = new PlanarAirlineGenerator.AirlineConfig();
        config.setFlightHeight(generatorPlanarAirlineRequestDTO.getHeight());       // 更低空飞行50米，提高精度
        config.setOverlapH(generatorPlanarAirlineRequestDTO.getOverlapH());                              // 高航向重叠率85%
//        config.setOverlapH(85);                              // 高航向重叠率85%
//        config.setOverlapW(75);                              // 高旁向重叠率75%
        config.setOverlapW(generatorPlanarAirlineRequestDTO.getOverlapW());
//        config.setDirection(0);                              // 0度航线方向（北向）
        config.setDirection(generatorPlanarAirlineRequestDTO.getDirection());                              // 0度航线方向（北向）
        config.setMargin(0);                                 // 不允许超出边界
        config.setGaodeOptimized(true);                      // 启用高德地图优化
        config.setDirection(generatorPlanarAirlineRequestDTO.getDirection());
        // 使用高精度相机参数
        config.setFocalLength(2.0);                         // 35mm焦距
        config.setSensorWidth(36.0);
        config.setSensorHeight(24.0);
        config.setImageWidth(4000);                          // 超高分辨率
        config.setImageHeight(3000);
//        List<CoordinatePointReq> boundaryPoints = generateOptimizedCrescentPolygon();
        PlanarAirlineService.PlanarAirlineResult result =
//                PlanarAirlineService.generateCompletePlanarAirline(boundaryPoints, config, 25.0);
                PlanarAirlineService.generateCompletePlanarAirline(boundaryPoints, config, generatorPlanarAirlineRequestDTO.getSpeed());
//                PlanarAirlineService.generateCompletePlanarAirline(boundaryPoints, config, 7.0);
        System.out.println(result);
        DecimalFormat df = new DecimalFormat("#.00");
//        String formattedNumber = df.format(number);
        System.out.println(result);
        result.setTotalPhotos(result.getTotalPhotos());
        result.setExecuteTime(Double.valueOf(df.format(result.getEstimatedFlightTime())));
        result.setEstimatedFlightTime(Double.valueOf(df.format(result.getEstimatedFlightTime())));
        result.setCoverageArea(Double.valueOf(df.format(result.getCoverageArea())));
        result.setTotalDistance(Double.valueOf(df.format(result.getTotalDistance())));

        long totalSeconds = (long) result.getEstimatedFlightTime(); // 使用long类型以避免溢出
        Duration duration = Duration.ofSeconds(totalSeconds);
        String formattedTime = duration.toString().substring(2); // 移除PT部分，只保留时间字符串
        System.out.println(formattedTime);

//        Duration duration = Duration.ofSeconds(totalSeconds);
        System.out.println(duration.toHours() + "小时 " + duration.toMinutesPart() + "分钟 " + duration.getSeconds() % 60 + "秒");
        GetPlanarAirlineResultResponseDTO getPlanarAirlineResultResponseDTO = new GetPlanarAirlineResultResponseDTO();
        getPlanarAirlineResultResponseDTO.setTotalPhotos(result.getTotalPhotos());
        getPlanarAirlineResultResponseDTO.setCoverageArea(result.getCoverageArea());
        getPlanarAirlineResultResponseDTO.setTotalDistance(result.getTotalDistance());
        getPlanarAirlineResultResponseDTO.setExecuteTime(result.getEstimatedFlightTime());
        String timestr = "";
        if (duration.toHours()== 0) {
            timestr = duration.toMinutesPart() + "min" + duration.getSeconds() % 60 + "s";
        }else{
            timestr = duration.toHours() + "h" + duration.toMinutesPart() + "min" + duration.getSeconds() % 60 + "s";
        }
        getPlanarAirlineResultResponseDTO.setEstimatedFlightTime(timestr);
        getPlanarAirlineResultResponseDTO.setFlightPath(result.getFlightPath());
        getPlanarAirlineResultResponseDTO.setTotalPhotos(result.getEstimatedPhotoCount());
        getPlanarAirlineResultResponseDTO.setEstimatedPhotoCount(result.getEstimatedPhotoCount());
        return getPlanarAirlineResultResponseDTO;
    }

    @Override
    public Long copyAirline(Long airlineId){
        FeisuanAirline feisuanAirline = airlineMapper.selectById(airlineId);
        if(feisuanAirline == null){
            return null;
        }
        feisuanAirline.setId(null);
        feisuanAirline.setIsCopy(1);
        airlineMapper.insert(feisuanAirline);
        Long newId = feisuanAirline.getId();

        //查询航点
        QueryWrapper<FeisuanWayPoint> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("airline_id", airlineId);

        List<FeisuanWayPoint> feisuanWayPoints = wayPointMapper.selectList(queryWrapper);
        for (FeisuanWayPoint feisuanWayPoint : feisuanWayPoints) {
            Long feisuanWayPointId = feisuanWayPoint.getId();
            feisuanWayPoint.setId(null);
            feisuanWayPoint.setAirlineId(newId);
            wayPointMapper.insert(feisuanWayPoint);
            Long newWayPointId = feisuanWayPoint.getId();
            QueryWrapper<FeisuanWayPointAction> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("way_point_id", feisuanWayPointId);
            List<FeisuanWayPointAction> list = wayPointActionMapper.selectList(queryWrapper2);
            for (FeisuanWayPointAction feisuanWayPointAction : list) {
                feisuanWayPointAction.setId(null);
                feisuanWayPointAction.setWayPointId(newWayPointId);
                wayPointActionMapper.insert(feisuanWayPointAction);
            }
        }
        return newId;
    }
    @Override
    public void updatePlanarAirline(AddPlanarAirlineRequestDTO addPlanarAirlineRequestDTO) throws IOException {
        FeisuanAirline feisuanPlanarAirline = BeanUtil.copyProperties(addPlanarAirlineRequestDTO, FeisuanAirline.class);
        QueryWrapper<FeisuanAirline> queryWrapperOld = new QueryWrapper<>();
        queryWrapperOld.eq("airline_name", addPlanarAirlineRequestDTO.getAirlineName());

        queryWrapperOld.ne("id", addPlanarAirlineRequestDTO.getId());
        queryWrapperOld.last("limit 1");
        queryWrapperOld.eq("is_copy",0);
        FeisuanAirline feisuanAirline1 = airlineMapper.selectOne(queryWrapperOld);
        if (ObjectUtil.isNotNull(feisuanAirline1)) {
            throw new RuntimeException("航线名称已存在");
        }
        airlineMapper.updateById(feisuanPlanarAirline);
        Long id = feisuanPlanarAirline.getId();
        Boolean isCreatFile = false;
        //无边界
        if (!CollectionUtils.isEmpty(addPlanarAirlineRequestDTO.getCoordinatePointReqList())){
            List<CoordinatePointReq> addCoordinatePoints = addPlanarAirlineRequestDTO.getCoordinatePointReqList();
            List<FeisuanCoordinatePoint> feisuanCoordinatePoints = BeanUtil.copyToList(addCoordinatePoints, FeisuanCoordinatePoint.class);

            //删除之前的航点
            QueryWrapper<FeisuanWayPoint> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("airline_id", addPlanarAirlineRequestDTO.getId());
            wayPointMapper.delete(queryWrapper);
            //删除之前的航点
            QueryWrapper<FeisuanCoordinatePoint> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("airline_id", addPlanarAirlineRequestDTO.getId());
            coordinatePointMapper.delete(queryWrapper2);
            if (ObjectUtil.isNotEmpty(feisuanCoordinatePoints)) {
                Db.saveBatch(feisuanCoordinatePoints.stream().map(i -> {
                    i.setAirlineId(id);
                    return i;
                }).collect(Collectors.toList()));

            }

            isCreatFile = true;
        }
        List<CoordinatePointReq> addWayPoint = addPlanarAirlineRequestDTO.getWayPoints();
        if (!CollectionUtils.isEmpty(addPlanarAirlineRequestDTO.getWayPoints())){

            List<FeisuanWayPoint> feisuanWayPoints = BeanUtil.copyToList(addWayPoint, FeisuanWayPoint.class);
            if (ObjectUtil.isNotEmpty(feisuanWayPoints)) {
                Db.saveBatch(feisuanWayPoints.stream().map(i -> {
                    i.setAirlineId(id);
                    return i;
                }).collect(Collectors.toList()));
            }
        }else{
            isCreatFile = false;
        }


        if (isCreatFile) {
            List<CoordinatePointReq> boundaryPoints = addPlanarAirlineRequestDTO.getCoordinatePointReqList();
            PlanarAirlineGenerator.AirlineConfig config = new PlanarAirlineGenerator.AirlineConfig();
            config.setFlightHeight(addPlanarAirlineRequestDTO.getHeight());       // 更低空飞行50米，提高精度
            config.setOverlapH(addPlanarAirlineRequestDTO.getOverlapH());                              // 高航向重叠率85%
            config.setOverlapW(addPlanarAirlineRequestDTO.getOverlapW());
//        config.setDirection(0);                              // 0度航线方向（北向）
            config.setDirection(addPlanarAirlineRequestDTO.getDirection());                              // 0度航线方向（北向）
            config.setMargin(0);                                 // 不允许超出边界
            config.setGaodeOptimized(true);                      // 启用高德地图优化
            config.setDirection(addPlanarAirlineRequestDTO.getDirection());
            // 使用高精度相机参数
            config.setFocalLength(2.0);                         // 35mm焦距
            config.setSensorWidth(36.0);
            config.setSensorHeight(24.0);
            config.setImageWidth(8000);                          // 超高分辨率
            config.setImageHeight(6000);
            PlanarAirlineService.PlanarAirlineResult airlineResult = new PlanarAirlineService.PlanarAirlineResult();
            airlineResult.setFlightPath(addWayPoint);

            WpmzFileGenerator.WpmzConfig wpmzConfig = new WpmzFileGenerator.WpmzConfig();
            System.out.println("\n生成WPMZ文件（自定义配置 + 原始边界）...");
            wpmzConfig.setFileName("mzhx");
            wpmzConfig.setFlightHeight(addPlanarAirlineRequestDTO.getHeight());  // 低空飞行
            wpmzConfig.setFlightSpeed(Double.valueOf(addPlanarAirlineRequestDTO.getAutoFlightSpeed().toString()));                    // 较快速度
            MappingTypeReq mappingTypeReq = new MappingTypeReq();
            switch (addPlanarAirlineRequestDTO.getShootType()) {
                case 0:
                    mappingTypeReq.setShootType(ShootTypeEnums.TIME.getValue());
                    break;
                case 1:
                    mappingTypeReq.setShootType(ShootTypeEnums.DISTANCE.getDescription());
                    break;
            }
            wpmzConfig.setMappingTypeReq(mappingTypeReq);
            mappingTypeReq.setMargin(addPlanarAirlineRequestDTO.getMargin().toString());
            mappingTypeReq.setLensType(LensTypeEnums.LIDAR.getValue());
            mappingTypeReq.setDirection(addPlanarAirlineRequestDTO.getDirection().toString());
            mappingTypeReq.setElevationOptimizeEnable(addPlanarAirlineRequestDTO.getElevationOptimizeEnable());
            mappingTypeReq.setCollectionMethod(CollectionMethodEnums.ORTHO.getValue());
            FeisuanDeviceModel feisuanDeviceModel = deviceMapper.selectById(addPlanarAirlineRequestDTO.getModelId());
            System.out.println("无人机型号:"+JSON.toJSONString(feisuanDeviceModel));
            if (ObjectUtil.isNotNull(feisuanDeviceModel)) {
                wpmzConfig.setDroneEnumValue(Integer.valueOf( feisuanDeviceModel.getType()));
                wpmzConfig.setDroneSubEnumValue(Integer.valueOf(feisuanDeviceModel.getSubType()));
            }
            // 特定无人机型号
            wpmzConfig.setTemplateType("mapping2d");           // 建图航拍模式
            wpmzConfig.setAuthor("PlanarAirlineExample");
            WpmzFileGenerator.WpmzGenerationResult wpmzResult2 =
                    WpmzFileGenerator.generateWpmzFromAirlineResultWithBoundary(
                            airlineResult, boundaryPoints, wpmzConfig);
            System.out.println("自定义配置WPMZ结果（使用原始边界）：");
            System.out.println("文件路径: " + wpmzResult2.getWpmzFilePath());
            File file = new File(wpmzResult2.getWpmzFilePath());
            String s1 = MD5.create().digestHex(file);
            MinioUtil minioUtil = new MinioUtil();
            MultipartFile multipartFile = FileUtils.fileToMultipartFile(file, wpmzResult2.getWpmzFilePath());
            Map<String,Object> fileInfo =  minioUtil.uploadFile(multipartFile,"my-bucket","airline");
            if (ObjectUtil.isNotNull(fileInfo)) {
                feisuanPlanarAirline.setAirlineUrl(fileInfo.get("url").toString());
                feisuanPlanarAirline.setETag(s1);
                feisuanPlanarAirline.setPointNum(addWayPoint.size());

            }
        }
        airlineMapper.updateById(feisuanPlanarAirline);

    }

    @Override
    public void addPlanarAirline(AddPlanarAirlineRequestDTO addPlanarAirlineRequestDTO) throws IOException {
        FeisuanAirline feisuanPlanarAirline = BeanUtil.copyProperties(addPlanarAirlineRequestDTO, FeisuanAirline.class);
        feisuanPlanarAirline.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        feisuanPlanarAirline.setCreateTime(LocalDateTime.now());
        feisuanPlanarAirline.setAirlineCode(UUID.randomUUID().toString());


        airlineMapper.insert(feisuanPlanarAirline);
        Long id = feisuanPlanarAirline.getId();

        List<CoordinatePointReq> addCoordinatePoints = addPlanarAirlineRequestDTO.getCoordinatePointReqList();
        List<CoordinatePointReq> addWayPoint = addPlanarAirlineRequestDTO.getWayPoints();
        List<FeisuanCoordinatePoint> feisuanCoordinatePoints = BeanUtil.copyToList(addCoordinatePoints, FeisuanCoordinatePoint.class);
        System.out.println(addWayPoint);
        List<FeisuanWayPoint> feisuanWayPoints = BeanUtil.copyToList(addWayPoint, FeisuanWayPoint.class);

        Db.saveBatch(feisuanCoordinatePoints.stream().map(i -> {
            i.setAirlineId(id);
            return i;
        }).collect(Collectors.toList()));

        Db.saveBatch(feisuanWayPoints.stream().map(i -> {
            i.setAirlineId(id);
            return i;
        }).collect(Collectors.toList()));
        List<CoordinatePointReq> boundaryPoints = addPlanarAirlineRequestDTO.getCoordinatePointReqList();
        PlanarAirlineGenerator.AirlineConfig config = new PlanarAirlineGenerator.AirlineConfig();
        config.setFlightHeight(addPlanarAirlineRequestDTO.getHeight());       // 更低空飞行50米，提高精度
        config.setOverlapH(addPlanarAirlineRequestDTO.getOverlapH());                              // 高航向重叠率85%
//        config.setOverlapH(85);                              // 高航向重叠率85%
//        config.setOverlapW(75);                              // 高旁向重叠率75%
        config.setOverlapW(addPlanarAirlineRequestDTO.getOverlapW());
//        config.setDirection(0);                              // 0度航线方向（北向）
        config.setDirection(addPlanarAirlineRequestDTO.getDirection());                              // 0度航线方向（北向）
        config.setMargin(0);                                 // 不允许超出边界
        config.setGaodeOptimized(true);                      // 启用高德地图优化
        config.setDirection(addPlanarAirlineRequestDTO.getDirection());
        // 使用高精度相机参数
        config.setFocalLength(2.0);                         // 35mm焦距
        config.setSensorWidth(36.0);
        config.setSensorHeight(24.0);
        config.setImageWidth(8000);                          // 超高分辨率
        config.setImageHeight(6000);
        PlanarAirlineService.PlanarAirlineResult airlineResult = new PlanarAirlineService.PlanarAirlineResult();
        airlineResult.setFlightPath(addWayPoint);
//        PlanarAirlineService.PlanarAirlineResult airlineResult =
//                PlanarAirlineService.generateCompletePlanarAirline(boundaryPoints, config, 15.0);

        WpmzFileGenerator.WpmzConfig wpmzConfig = new WpmzFileGenerator.WpmzConfig();
        System.out.println("\n生成WPMZ文件（自定义配置 + 原始边界）...");
        wpmzConfig.setFileName("mzhx");
        wpmzConfig.setFlightHeight(addPlanarAirlineRequestDTO.getHeight());  // 低空飞行
        wpmzConfig.setFlightSpeed(Double.valueOf(addPlanarAirlineRequestDTO.getAutoFlightSpeed().toString()));                    // 较快速度
        MappingTypeReq mappingTypeReq = new MappingTypeReq();
        switch (addPlanarAirlineRequestDTO.getShootType()) {
            case 0:
                mappingTypeReq.setShootType(ShootTypeEnums.TIME.getValue());
                break;
            case 1:
                mappingTypeReq.setShootType(ShootTypeEnums.DISTANCE.getDescription());
                break;
        }
        wpmzConfig.setMappingTypeReq(mappingTypeReq);
        mappingTypeReq.setMargin(addPlanarAirlineRequestDTO.getMargin().toString());
        mappingTypeReq.setLensType(LensTypeEnums.LIDAR.getValue());
        mappingTypeReq.setDirection(addPlanarAirlineRequestDTO.getDirection().toString());
        mappingTypeReq.setElevationOptimizeEnable(addPlanarAirlineRequestDTO.getElevationOptimizeEnable());
        mappingTypeReq.setCollectionMethod(CollectionMethodEnums.ORTHO.getValue());
        FeisuanDeviceModel feisuanDeviceModel = deviceMapper.selectById(addPlanarAirlineRequestDTO.getModelId());

        if (ObjectUtil.isNotNull(feisuanDeviceModel)) {
            wpmzConfig.setDroneEnumValue(Integer.valueOf( feisuanDeviceModel.getType()));
            wpmzConfig.setDroneSubEnumValue(Integer.valueOf(feisuanDeviceModel.getSubType()));
        }
                          // 特定无人机型号
        wpmzConfig.setTemplateType("mapping2d");           // 建图航拍模式
        wpmzConfig.setAuthor("PlanarAirlineExample");
        WpmzFileGenerator.WpmzGenerationResult wpmzResult2 =
                WpmzFileGenerator.generateWpmzFromAirlineResultWithBoundary(
                        airlineResult, boundaryPoints, wpmzConfig);
        System.out.println("自定义配置WPMZ结果（使用原始边界）：");
        System.out.println("文件路径: " + wpmzResult2.getWpmzFilePath());
//        String s = RouteFileUtils.buildKmz(kmlParamsExtension, fileName, kmlParams);
        File file = new File(wpmzResult2.getWpmzFilePath());
        String s1 = MD5.create().digestHex(file);
        MinioUtil minioUtil = new MinioUtil();
        MultipartFile multipartFile = FileUtils.fileToMultipartFile(file, wpmzResult2.getWpmzFilePath());
//        R<PutFileResponse> putFileResponseR = ossApi.putkmlFile(s, multipartFile);
        Map<String,Object> fileInfo =  minioUtil.uploadFile(multipartFile,"my-bucket","airline");
        if (ObjectUtil.isNotNull(fileInfo)) {
//            Map<String, Object> fileInfo = minioUtil.uploadFile(multipartFile,"my-bucket","zip");
            feisuanPlanarAirline.setAirlineUrl(fileInfo.get("url").toString());
            feisuanPlanarAirline.setETag(s1);
            airlineMapper.updateById(feisuanPlanarAirline);
        }

    }


    public void addPlanarAirlineOld(AddPlanarAirlineRequestDTO addPlanarAirlineRequestDTO) throws IOException {
        FeisuanPlanarAirline feisuanPlanarAirline = BeanUtil.copyProperties(addPlanarAirlineRequestDTO, FeisuanPlanarAirline.class);
        feisuanPlanarAirline.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        feisuanPlanarAirline.setCreateTime(LocalDateTime.now());
        feisuanPlanarAirline.setAirlineCode(UUID.randomUUID().toString());


        planarAirlineMapper.insert(feisuanPlanarAirline);
        Long id = feisuanPlanarAirline.getId();


        List<CoordinatePointReq> addCoordinatePoints = addPlanarAirlineRequestDTO.getCoordinatePointReqList();
        List<FeisuanCoordinatePoint> feisuanCoordinatePoints = BeanUtil.copyToList(addCoordinatePoints, FeisuanCoordinatePoint.class);

        Db.saveBatch(feisuanCoordinatePoints.stream().map(i -> {
            i.setAirlineId(id);
            return i;
        }).collect(Collectors.toList()));

        String takeOffRefPoint = addPlanarAirlineRequestDTO.getTakeOffRefPoint();
        String[] split = takeOffRefPoint.split(",");
        //119.905782,30.251387,120
        BigDecimal longitude = new BigDecimal(split[0]);
        BigDecimal latitude = new BigDecimal(split[1]);
        BigDecimal height = new BigDecimal(split[2]);

        CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.gcj02ToWgs84(longitude, latitude);
        addPlanarAirlineRequestDTO.setTakeOffRefPoint(coordinate.getLatitude() + "," + coordinate.getLongitude() + "," + height.toString());

        addPlanarAirlineRequestDTO.getCoordinatePointReqList().forEach(i -> {
            BigDecimal latitude1 = i.getLatitude();
            BigDecimal longitude1 = i.getLongitude();
            CoordinateTransformUtil.Coordinate coordinate1 = CoordinateTransformUtil.gcj02ToWgs84(longitude1, latitude1);
            i.setLatitude(coordinate1.getLatitude());
            i.setLongitude(coordinate1.getLongitude());
        });


        GeneratePlanarAirlineRequest generatePlanarAirlineRequest = BeanUtil.copyProperties(addPlanarAirlineRequestDTO, GeneratePlanarAirlineRequest.class);
        R<GenerateAirlineFileResponse> generateAirlineFileResponseR = flightTaskApi.generatePlanarAirline(generatePlanarAirlineRequest);
        if (ObjectUtil.isNotNull(generateAirlineFileResponseR)
                && ObjectUtil.isNotNull(generateAirlineFileResponseR.getData())) {
            UpdateWrapper<FeisuanPlanarAirline> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id);
            updateWrapper.set("e_tag", generateAirlineFileResponseR.getData().getETag());
            updateWrapper.set("airline_url", generateAirlineFileResponseR.getData().getUrl());
            planarAirlineMapper.update(null, updateWrapper);
        }

    }

//    @Override
//    public void updatePlanarAirline(UpdatePlanarAirlineRequestDTO updatePlanarAirlineRequestDTO) throws IOException {
//        try {
//            // 先删除子航点
//            Long airlineId = updatePlanarAirlineRequestDTO.getId();
//            UpdateWrapper<FeisuanCoordinatePoint> feisuanCoordinatePointUpdateWrapper = new UpdateWrapper<>();
//            feisuanCoordinatePointUpdateWrapper.eq("airline_id", airlineId);
//            coordinatePointMapper.delete(feisuanCoordinatePointUpdateWrapper);
//
//            // 更新数据
//            UpdateWrapper<FeisuanPlanarAirline> feisuanPlanarAirlineUpdateWrapper = new UpdateWrapper<>();
//            feisuanPlanarAirlineUpdateWrapper.eq("id", airlineId);
//            feisuanPlanarAirlineUpdateWrapper.set(
//                            StrUtil.isNotBlank(updatePlanarAirlineRequestDTO.getAirlineName()),
//                            "airline_name", updatePlanarAirlineRequestDTO.getAirlineName()
//                    ).set(
//                            ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getAirlineType()),
//                            "airline_type", updatePlanarAirlineRequestDTO.getAirlineType()
//                    ).set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getAreas()),
//                            "areas", updatePlanarAirlineRequestDTO.getAreas())
//                    .set(StrUtil.isNotBlank(updatePlanarAirlineRequestDTO.getExecuteTime()),
//                            "execute_time", updatePlanarAirlineRequestDTO.getExecuteTime())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getDirection()),
//                            "direction", updatePlanarAirlineRequestDTO.getDirection())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getAutoFlightSpeed()),
//                            "auto_flight_speed", updatePlanarAirlineRequestDTO.getAutoFlightSpeed())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getFinishAction()),
//                            "finish_action", updatePlanarAirlineRequestDTO.getFinishAction())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getCollectType()),
//                            "collect_type", updatePlanarAirlineRequestDTO.getCollectType())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getElevationOptimizeEnable()),
//                            "elevation_optimize_enable", updatePlanarAirlineRequestDTO.getElevationOptimizeEnable())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getGimbalPitchAngle()),
//                            "gimbal_pitch_angle", updatePlanarAirlineRequestDTO.getGimbalPitchAngle())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getGlobalShootHeight())
//                            , "global_shoot_height", updatePlanarAirlineRequestDTO.getGlobalShootHeight())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getGlobalTransitionalSpeed()),
//                            "global_transitional_speed", updatePlanarAirlineRequestDTO.getGlobalTransitionalSpeed())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getHeight()), "height",
//                            updatePlanarAirlineRequestDTO.getHeight())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getHeightMode()),
//                            "height_mode", updatePlanarAirlineRequestDTO.getHeightMode())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getIrTypeSupport()),
//                            "ir_type_support", updatePlanarAirlineRequestDTO.getIrTypeSupport())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getWideTypeSupport()),
//                            "wide_type_support", updatePlanarAirlineRequestDTO.getWideTypeSupport())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getMargin()),
//                            "margin", updatePlanarAirlineRequestDTO.getMargin())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getOverlapH()),
//                            "overlap_h", updatePlanarAirlineRequestDTO.getOverlapH())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getOverlapW()),
//                            "overlap_w", updatePlanarAirlineRequestDTO.getOverlapW())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getShootType()),
//                            "shoot_type", updatePlanarAirlineRequestDTO.getShootType())
//                    .set(StrUtil.isNotBlank(updatePlanarAirlineRequestDTO.getTakeOffRefPoint()),
//                            "take_off_ref_point", updatePlanarAirlineRequestDTO.getTakeOffRefPoint())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getTakeOffSecurityHeight()),
//                            "take_off_security_height", updatePlanarAirlineRequestDTO.getTakeOffSecurityHeight())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getTotalDistance()),
//                            "total_distance", updatePlanarAirlineRequestDTO.getTotalDistance())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getTotalPhotos()),
//                            "total_photos", updatePlanarAirlineRequestDTO.getTotalPhotos())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getWaypointHeadingAngle()),
//                            "waypoint_heading_angle", updatePlanarAirlineRequestDTO.getWaypointHeadingAngle())
//                    .set(ObjectUtil.isNotNull(updatePlanarAirlineRequestDTO.getWaypointHeadingMode()),
//                            "waypoint_heading_mode", updatePlanarAirlineRequestDTO.getWaypointHeadingMode())
//            ;
//
//            planarAirlineMapper.update(null, feisuanPlanarAirlineUpdateWrapper);
//
//
//            //重新添加航点
//
//            List<UpdateCoordinatePointReqDTO> updateCoordinatePointReqs = updatePlanarAirlineRequestDTO.getCoordinatePointReqList();
//            List<FeisuanCoordinatePoint> feisuanCoordinatePoints = BeanUtil.copyToList(updateCoordinatePointReqs, FeisuanCoordinatePoint.class);
//            feisuanCoordinatePoints.forEach(feisuanCoordinatePoint -> {
//                feisuanCoordinatePoint.setAirlineId(updatePlanarAirlineRequestDTO.getId());
//            });
//            Db.saveBatch(feisuanCoordinatePoints);
//
//            updatePlanarAirlineRequestDTO.getCoordinatePointReqList().forEach(i -> {
//                BigDecimal latitude1 = i.getLatitude();
//                BigDecimal longitude1 = i.getLongitude();
//                CoordinateTransformUtil.Coordinate coordinate1 = CoordinateTransformUtil.gcj02ToWgs84(longitude1, latitude1);
//                i.setLatitude(coordinate1.getLatitude());
//                i.setLongitude(coordinate1.getLongitude());
//            });
//
//
//            String takeOffRefPoint = updatePlanarAirlineRequestDTO.getTakeOffRefPoint();
//            String[] split = takeOffRefPoint.split(",");
//            //119.905782,30.251387,120
//            BigDecimal longitude = new BigDecimal(split[0]);
//            BigDecimal latitude = new BigDecimal(split[1]);
//            BigDecimal height = new BigDecimal(split[2]);
//
//            CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.gcj02ToWgs84(longitude, latitude);
//            updatePlanarAirlineRequestDTO.setTakeOffRefPoint(coordinate.getLatitude() + "," + coordinate.getLongitude() + "," + height.toString());
//
//
//            GeneratePlanarAirlineRequest generatePlanarAirlineRequest = BeanUtil.copyProperties(updatePlanarAirlineRequestDTO, GeneratePlanarAirlineRequest.class);
//
//            //更新航线文件
//
//            R<GenerateAirlineFileResponse> generateAirlineFileResponseR = flightTaskApi.generatePlanarAirline(generatePlanarAirlineRequest);
//            if (ObjectUtil.isNotNull(generateAirlineFileResponseR)
//                    && ObjectUtil.isNotNull(generateAirlineFileResponseR.getData())) {
//                UpdateWrapper<FeisuanPlanarAirline> updateWrapper = new UpdateWrapper<>();
//                updateWrapper.eq("id", updatePlanarAirlineRequestDTO.getId());
//                updateWrapper.set("e_tag", generateAirlineFileResponseR.getData().getETag());
//                updateWrapper.set("airline_url", generateAirlineFileResponseR.getData().getUrl());
//                planarAirlineMapper.update(null, updateWrapper);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//
//    }

    @Override
    public GetAirlineByAirlineCodeResponseDTO getAirlineByAirlineCode(GetAirlineByAirlineCodeRequestDTO getAirlineByAirlineCodeRequestDTO) {
        QueryWrapper<FeisuanAirline> feisuanAirlineQueryWrapper = new QueryWrapper<>();
        feisuanAirlineQueryWrapper.eq("airline_code", getAirlineByAirlineCodeRequestDTO.getAirlineCode());
        FeisuanAirline feisuanAirline = airlineMapper.selectOne(feisuanAirlineQueryWrapper);


        if (ObjectUtil.isNotNull(feisuanAirline)) {
            GetAirlineByAirlineCodeResponseDTO getAirlineByAirlineCodeResponseDTO = BeanUtil.copyProperties(feisuanAirline, GetAirlineByAirlineCodeResponseDTO.class);
//        String takeOffRefPoint = getAirlineByIdResponseDTO.getTakeOffRefPoint();
//        String s = CoordinateTransformUtil.wgs84StringToGcj02StringBigDecimal(takeOffRefPoint);
//        getAirlineByIdResponseDTO.setTakeOffRefPoint(s);

            QueryWrapper<FeisuanWayPoint> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("airline_id", feisuanAirline.getId());
            List<FeisuanWayPoint> feisuanWayPoints = wayPointMapper.selectList(queryWrapper);
            getAirlineByAirlineCodeResponseDTO.setWayPoints(BeanUtil.copyToList(feisuanWayPoints, GetWayPointByAirlineCodeResponseDTO.class));
            getAirlineByAirlineCodeResponseDTO.getWayPoints().forEach(wayPoint -> {
                QueryWrapper<FeisuanWayPointAction> feisuanWayPointActionQueryWrapper = new QueryWrapper<>();
                feisuanWayPointActionQueryWrapper.eq("way_point_id", wayPoint.getId());
                List<FeisuanWayPointAction> feisuanWayPointActions = wayPointActionMapper.selectList(feisuanWayPointActionQueryWrapper);
                wayPoint.setActions(BeanUtil.copyToList(feisuanWayPointActions, GetWayPointActionByIdResponseDTO.class));


                QueryWrapper<FeisuanAlgorithm> feisuanAlgorithmQueryWrapper = new QueryWrapper<>();
                feisuanAlgorithmQueryWrapper.eq("way_point_id", wayPoint.getId());
                List<FeisuanAlgorithm> feisuanAlgorithms = algorithmMapper.selectList(feisuanAlgorithmQueryWrapper);
                if (CollectionUtil.isNotEmpty(feisuanAlgorithms)) {
                    List<Integer> collect = feisuanAlgorithms.stream().map(algorithm -> algorithm.getAlgorithmId()).collect(Collectors.toList());
                    wayPoint.setAlgorithmIds(collect);
                } else {
                    wayPoint.setAlgorithmIds(new ArrayList<>());
                }
                QueryWrapper<FeisuanAlgorithmExtends> feisuanAlgorithmExtendsQueryWrapper = new QueryWrapper<>();
                feisuanAlgorithmExtendsQueryWrapper.eq("way_point_id", wayPoint.getId());
                List<FeisuanAlgorithmExtends> feisuanAlgorithmExtends = algorithmExtendsMapper.selectList(feisuanAlgorithmExtendsQueryWrapper);
                if (CollectionUtil.isNotEmpty(feisuanAlgorithmExtends)) {

                    wayPoint.setAlgorithmExtendsByIds(BeanUtil.copyToList(feisuanAlgorithmExtends, GetAlgorithmExtendsByIdResponseDTO.class));
                } else {
                    wayPoint.setAlgorithmExtendsByIds(new ArrayList<>());
                }

                QueryWrapper<FeisuanMegaphoneOperate> feisuanMegaphoneOperateQueryWrapper = new QueryWrapper<>();
                feisuanMegaphoneOperateQueryWrapper.eq("way_point_id", wayPoint.getId());
                List<FeisuanMegaphoneOperate> feisuanMegaphoneOperates = megaphoneOperateMapper.selectList(feisuanMegaphoneOperateQueryWrapper);
                if (CollectionUtil.isNotEmpty(feisuanMegaphoneOperates)) {
                    wayPoint.setMegaphoneOperate(BeanUtil.copyProperties(feisuanMegaphoneOperates.get(0), GetMegaphoneOperateByIdResponseDTO.class));
                }
            });
            return getAirlineByAirlineCodeResponseDTO;
        } else {
            QueryWrapper<FeisuanPlanarAirline> feisuanPlanarAirlineQueryWrapper = new QueryWrapper<>();
            feisuanPlanarAirlineQueryWrapper.eq("airline_code", getAirlineByAirlineCodeRequestDTO.getAirlineCode());
            List<FeisuanPlanarAirline> feisuanPlanarAirlines = planarAirlineMapper.selectList(feisuanPlanarAirlineQueryWrapper);
            if (CollectionUtil.isEmpty(feisuanPlanarAirlines)) {
                throw new RuntimeException("航线不存在");
            } else {
                GetAirlineByAirlineCodeResponseDTO getAirlineByAirlineCodeResponseDTO = BeanUtil.copyProperties(feisuanPlanarAirlines.get(0), GetAirlineByAirlineCodeResponseDTO.class);
                QueryWrapper<FeisuanCoordinatePoint> feisuanCoordinatePointQueryWrapper = new QueryWrapper<>();
                feisuanCoordinatePointQueryWrapper.eq("airline_id", feisuanPlanarAirlines.get(0).getId());
                List<FeisuanCoordinatePoint> feisuanCoordinatePoints = coordinatePointMapper.selectList(feisuanCoordinatePointQueryWrapper);
                getAirlineByAirlineCodeResponseDTO.setCoordinatePointReqList(BeanUtil.copyToList(feisuanCoordinatePoints, GetCoordinatePointByAirlineCodeResponseDTO.class));
                return getAirlineByAirlineCodeResponseDTO;
            }
        }
//        return getAirlineByIdResponseDTO;
    }
}
